# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
require 'csv'

# Seed data configuration filename.
config_filename = "#{RAILS_ROOT}/db/seeds.yml"
raise "#{config_filename} not found." if not File.exists? config_filename

seeds = YAML.load_file(config_filename)

# Create user record.
user = User.create(:email => 'testuser@example.com', :password => 'fragment')
      
# Create job records from seed data.
seeds.each do |job|
  current_job = Job.create(:mol_file => %{#{open("#{RAILS_ROOT}/#{job['mol_file']}", 'r').read()}},
    :ms_file             => open("#{RAILS_ROOT}/#{job["ms_file"]}", 'r').read(),
    :measurement_error   => job['diff'], 
    :intensity_threshold => job['intensity'], 
    :rr                  => job['rr'] == 1 ? true : false, 
    :cuts                => job['cuts'],
    :description         => %{Test data for molecule #{job['formula']}.}
  )

  current_job.user = user 
  current_job.formula = job['formula']
  current_job.completed = true
  current_job.save

  # used to keep track of the peak number the current
  #fragment belongs to so we can select the first fragment
  #for each peak.
  peaknum = 0

  # Create fragment records from seed data.
  CSV.open("#{RAILS_ROOT}/#{job['out_file']}", 'r', "\t").each do |row|
    Fragment.create(:job => current_job,
      :selected => if row[1].to_i > peaknum then peaknum = row[1].to_i; true else false end,
      :fragment => row[0].to_i,
      :peaknum  => row[1].to_i, 
      :peakmass => row[2].to_f,
      :mass     => row[3].to_f, 
      :massdiff => row[4].to_f,
      :formula  => row[5],
      :atombits => row[6], 
      :rank     => row[7].to_i,
      :score    => row[8].to_f, 
      :bb       => row[9].to_i, 
      :bbh      => row[10].to_i,
      :bbs      => row[11].to_i, 
      :abb      => row[12].to_i, 
      :sbb      => row[13].to_i, 
      :swd      => row[14].to_i,
      :rr       => row[15] == 'yes' ? true : false
    )
  end
end
